#!/bin/bash

# AI Daily - 服务状态检查脚本
echo "📊 AI Daily Services Status"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$SCRIPT_DIR/backend"

# 函数：检查端口状态
check_port_status() {
    local port=$1
    local service_name=$2
    local url=$3
    
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo -e "${GREEN}✅ $service_name is running on port $port${NC}"
        if [ ! -z "$url" ]; then
            echo -e "   🔗 $url"
        fi
        return 0
    else
        echo -e "${RED}❌ $service_name is not running on port $port${NC}"
        return 1
    fi
}

# 函数：检查进程状态
check_process_status() {
    local service_name=$1
    local pid_file=$2
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            echo -e "${GREEN}✅ $service_name process is running (PID: $pid)${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠️  $service_name PID file exists but process is not running${NC}"
            return 1
        fi
    else
        echo -e "${BLUE}ℹ️  No $service_name PID file found${NC}"
        return 1
    fi
}

echo ""
echo -e "${BLUE}=== Service Status ===${NC}"

# 检查后端状态
echo -e "${BLUE}🔧 Backend Service:${NC}"
check_port_status 8000 "FastAPI Backend" "http://localhost:8000"
check_process_status "Backend" "$BACKEND_DIR/backend.pid"

echo ""

# 检查前端状态
echo -e "${BLUE}📱 Frontend Service:${NC}"
check_port_status 3000 "React Frontend" "http://localhost:3000"
check_process_status "Frontend" "$SCRIPT_DIR/frontend.pid"

echo ""
echo -e "${BLUE}=== Log Files ===${NC}"

# 检查日志文件
if [ -f "$BACKEND_DIR/backend.log" ]; then
    local backend_log_size=$(wc -l < "$BACKEND_DIR/backend.log")
    echo -e "${GREEN}📋 Backend log: $backend_log_size lines${NC}"
    echo -e "   📄 $BACKEND_DIR/backend.log"
else
    echo -e "${YELLOW}⚠️  Backend log file not found${NC}"
fi

if [ -f "$SCRIPT_DIR/frontend.log" ]; then
    local frontend_log_size=$(wc -l < "$SCRIPT_DIR/frontend.log")
    echo -e "${GREEN}📋 Frontend log: $frontend_log_size lines${NC}"
    echo -e "   📄 $SCRIPT_DIR/frontend.log"
else
    echo -e "${YELLOW}⚠️  Frontend log file not found${NC}"
fi

echo ""
echo -e "${BLUE}=== Quick Actions ===${NC}"
echo -e "• Start services: ${GREEN}./start_services.sh${NC}"
echo -e "• Stop services:  ${GREEN}./stop_services.sh${NC}"
echo -e "• View backend logs: ${GREEN}tail -f backend/backend.log${NC}"
echo -e "• View frontend logs: ${GREEN}tail -f frontend.log${NC}"